package org.lex.ftp.ui.queue;

import java.util.Iterator;

import javax.swing.table.AbstractTableModel;

import org.lex.ftp.FTP;
import org.lex.ftp.queue.Task;
import org.lex.progress.Progress;
import org.lex.utils.text.SizeFormat;


public class QueueInfoTableModel extends AbstractTableModel {
	private static final String[] COLUMN_NAMES = { "", "Files", "Folders", "Size" };
	private static final String[] FIRST_COLUMN = { "Queue", "Failed", "Selected" };
	private String[][] data = null;

	public QueueInfoTableModel(FTP app) {
		this.data = new String[3][3];
		this.fillData(app);
	}

	private void fillData(FTP app) {
		long[][] d = new long[3][3];
		for (Iterator<Task> iter = app.getQueue().iterator(); iter.hasNext();) {
			Task t = iter.next();
			this.processTask(t, d[0]);
			if (Progress.Status.ERROR == t.getStatus())
				this.processTask(t, d[1]);
		}
		Task[] selected = app.getContentPane().getQueuePane().getSelectedTasks();
		for (Task t : selected)
			this.processTask(t, d[2]);
		for (int row = 0; row < data.length; row++)
			for (int column = 0; column < data[row].length; column++) {
				if (data[row].length - 1 == column)
					data[row][column] = SizeFormat.autoFormat(d[row][column]) + 'B';
				else
					data[row][column] = Long.toString(d[row][column]);
			}
	}

	private void processTask(Task t, long[] data) {
		if (t.hasChild())
			// #folders
			data[1]++;
		else {
			// #files
			data[0]++;
			// #size
			data[2] += t.getLength();
		}
	}

	@Override
	public Class<?> getColumnClass(int column) {
		return String.class;
	}

	@Override
	public String getColumnName(int column) {
		return COLUMN_NAMES[column];
	}

	public int getColumnCount() {
		return COLUMN_NAMES.length;
	}

	public int getRowCount() {
		return data.length;
	}

	public Object getValueAt(int row, int column) {
		if (0 == column)
			return FIRST_COLUMN[row];
		return data[row][column - 1];
	}
}
